#include "Screen.h"
#include "SDL.h"
#include "Game.h"
#include "ReportError.h"

Screen::Screen()
{
	m_surfDisplay = 0;
    m_isOpenGl = false;
}
Screen::~Screen()
{
}

int Screen::GetWidth()
{
    return m_width;
}
int Screen::GetHeight()
{
    return m_height;
}
bool Screen::Init(int height, int width, bool isOpenGl)
{
	//starts SDL
    if(SDL_Init(SDL_INIT_VIDEO) < 0) 
	{
        ReportError("SDL failed to initlaise the Screen: Missing SDL DLL?");
        return false;
    }

    //Set the member variable
    m_isOpenGl = isOpenGl;
    //Set up a stencil buffer
    SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE,8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE,8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE,8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE,8);
    SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE,8);

    m_maxHeight = SDL_GetVideoInfo()->current_h;
    m_maxWidth = SDL_GetVideoInfo()->current_w;
    m_height = height;
    m_width = width;
    if(m_isOpenGl)
    {
	    if((m_surfDisplay = SDL_SetVideoMode(width,height ,32, SDL_HWSURFACE | SDL_DOUBLEBUF  | SDL_OPENGL | SDL_NOFRAME)) == NULL) 
	    {
		    ReportError("Could not set video mode for SDL and OpenGL");
            return false;
        }   
    }
    else
    {
        if((m_surfDisplay = SDL_SetVideoMode(width, height ,32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_NOFRAME)) == NULL) 
	    {
		    ReportError("Could not set video mode for SDL");
            return false;
        }
    }

	return true;
}

void Screen::UpdateScreenSize(int height, int width)
{
    m_height = height;
    m_width = width;
}
void Screen::FullScreen()
{
    SDL_QuitSubSystem(SDL_INIT_VIDEO);
    SDL_Init(SDL_INIT_VIDEO);
    if((m_surfDisplay = SDL_SetVideoMode(m_maxWidth,m_maxHeight ,32, 
                                            SDL_HWSURFACE | 
                                            SDL_DOUBLEBUF | 
                                            SDL_OPENGL | 
                                            SDL_FULLSCREEN)) == NULL)
	{
		    ReportError("Could not set video mode for SDL");
    }
}


SDL_Surface* Screen::GetMain()
{
    if(m_isOpenGl)
    {
	    ReportError("The Main Screen is set to NULL because you are in OpenGL mode");
	    return NULL;
    }
	else if(m_surfDisplay != NULL)
	{
		return m_surfDisplay;
	}
    return NULL;
}

void Screen::Flip()
{
    if(m_isOpenGl)
    {
        SDL_GL_SwapBuffers();
    }
    else
    {
        if(SDL_Flip(m_surfDisplay) == -1)
	    {
		    ReportError("Flipping the main screens buffer has encountered an error");
	    }
    }
}

void Screen::CleanUp()
{
    if(m_surfDisplay)
	SDL_FreeSurface(m_surfDisplay);
}